import Button from '@/components/button'
import styles from './index.module.less'
import Input from '@/components/input'
import { useSetState } from 'ahooks'
import cm from 'classnames'
import { Fragment, useState } from 'react'
import CheckBox from '@/components/checkbox'
import { useCountDown } from 'ahooks'
import { register, getCode } from '@/api/user'
import { checkEmail, validPwd, surePwd, handleLocalUserInfo } from '@/utils/utils'
import { pick } from 'lodash-es'
import { cncryptionCipher } from '@/utils/encode'
import { debounce } from 'lodash-es'
import Toast from '@/components/toast'

const societyGroup = [
  {
    id: 1,
    name: '社交媒体',
  },
  {
    id: 2,
    name: '社群群组',
  },
  {
    id: 3,
    name: '网站',
  },
  {
    id: 4,
    name: '自研应用软件',
  },
  {
    id: 5,
    name: '其他',
  },
]

const Index = (props) => {
  const { roleGroup } = props
  const [formInfo, setFormInfo] = useSetState({
    step: 1,
    marketingModes: [],
    societyError: false,
    contractError: false,
    role: roleGroup[0].id,
    actorId: roleGroup[0].id,
  })
  const [targetDate, setTargetDate] = useState(0)

  const [countdown] = useCountDown({
    targetDate,
  })
  const { setUserToken } = handleLocalUserInfo()

  // 验证每一步数据是否正常
  const isStep2Pass = () => {
    if (!formInfo.marketingModes.length || !formInfo.marketingSites || !formInfo.flowDesc) {
      setFormInfo({
        societyError: !formInfo.marketingModes.length,
        websiteErr: !formInfo.marketingSites,
        flowErr: !formInfo.flowDesc,
        step: 2,
      })
      return false
    }
    return true
  }
  const isStep3Pass = () => {
    const isValidEmail = !checkEmail(formInfo.email)
    const isValidPwd = !validPwd(formInfo.password)
    const isSurePwd = !surePwd()
    const noContract = !formInfo.whatsapp && !formInfo.wechat && !formInfo.telegram
    if (isValidEmail || isValidPwd || isSurePwd || noContract || !formInfo.code) {
      setFormInfo({
        emailErr: isValidEmail,
        pwdErr: isValidPwd,
        repwdErr: isSurePwd,
        codeErr: !formInfo.code,
        contractError: noContract,
        step: 3,
      })
      return false
    }
    return true
  }

  // 跳转角色未开通页面 ///没有处理
  //提交
  const onSubmit = async () => {
    switch (formInfo.step) {
      case 1:
        setFormInfo({ step: 2 })
        break
      case 2:
        if (!isStep2Pass()) {
          return
        }
        setFormInfo({ step: 3 })
        break
      case 3:
        if (!isStep2Pass()) {
          return
        }
        if (!isStep3Pass()) {
          return
        }
        const res = await register({
          password: cncryptionCipher(formInfo.password),
          ...pick(formInfo, [
            'email',
            'code',
            'marketingModes',
            'actorId',
            'marketingSites',
            'flowDesc',
            'wechat',
            'whatsapp',
            'telegram',
          ]),
        })
        if (!res.code) {
          setUserToken(res.data.token)
          window.location.replace('/market-center')
        }
        break
      default:
        console.log('')
    }
  }

  //多选处理
  const handleSociety = (data) => {
    let oldData = [...formInfo.marketingModes]

    if (data.checked) {
      oldData.push(data.value)
    } else {
      oldData = oldData.filter((item) => item !== data.value)
    }
    setFormInfo({ marketingModes: oldData })
  }
  // 步骤1
  const step1 = (
    <div className={styles.stepsBox}>
      <p className={styles.title}>
        <span>请选择您想申请的首要权限类型!</span>
        <img src="/images/yes.webp" />
      </p>
      <p className={styles.chooseType}>此处为单选，账号注册成功后可申请其他营销权限</p>
      <div className={styles.roleChoose}>
        {roleGroup.map((item) => {
          return (
            <div
              key={item.id}
              className={cm(styles.roleItem, item.id === formInfo.role ? styles.roleItemActive : '')}
              onClick={() => setFormInfo({ role: item.id })}
            >
              <img src="/images/user.webp" alt="" className={styles.head} />
              <div className={styles.roleInfo}>
                <p className={styles.name}>{item.name}</p>
                <p className={styles.desc}>{item.desc}</p>
              </div>
              <div className={cm(styles.radio, item.id === formInfo.role ? styles.radioActive : '')}></div>
            </div>
          )
        })}
      </div>
    </div>
  )

  //步骤2
  const step2 = (
    <div className={styles.stepsBox}>
      <p className={styles.stepTitle}>
        <span className="text-red mr-1">*</span>
        <span>
          您是通过什么方式进行营销的? {'（'}可多选{'）'}
        </span>
        {formInfo.societyError && <span className={styles.error}>请至少选择一项</span>}
      </p>
      <div className={styles.checks}>
        {societyGroup.map((item) => {
          return (
            <CheckBox
              defaultChecked={formInfo.marketingModes.includes(item.name)}
              key={item.id}
              className={styles.space}
              value={item.name}
              name="marketingModes"
              bg="var(--theme-color)"
              onChange={handleSociety}
            >
              {item.name}
            </CheckBox>
          )
        })}
      </div>
      <p className={styles.stepTitle}>
        <span className="text-red mr-1">*</span>
        <span>请列出您的所选营销方式的网址</span>
        {formInfo.websiteErr && <span className={styles.error}>请输入</span>}
      </p>
      <Input
        inputClass="input"
        defaultValue={formInfo.marketingSites}
        onChange={(e) => setFormInfo({ marketingSites: e.currentTarget.value })}
        textarea
        placeholder="请在此输入您所有推广方式的网址"
      />
      <p className={styles.stepTitle}>
        <span className="text-red mr-1">*</span>
        <span>请简要描述您的流量类型</span>
        {formInfo.flowErr && <span className={styles.error}>请输入</span>}
      </p>
      <Input
        inputClass="input"
        defaultValue={formInfo.flowDesc}
        onChange={(e) => setFormInfo({ flowDesc: e.currentTarget.value })}
        textarea
        placeholder="请简要描述您的流量类型，如自然搜索、社交分享等"
      />
    </div>
  )

  // 步骤3
  const fetchCode = async () => {
    const isPass = checkEmail(formInfo.email)
    setFormInfo({ emailErr: !isPass })
    if (!isPass) {
      return
    }
    setTargetDate(Date.now() + 60000)
    const res = await getCode({ email: formInfo.email })
    if (!res.code) {
      Toast.normal('已发送验证码至邮箱，请查收')
    }
  }
  const debounceFetchCode = debounce(fetchCode, 300)
  const GetCodeDom = (
    <div className={styles.getCode}>
      {countdown ? (
        <span className={styles.wait}>{Math.round(countdown / 1000)}s后重发</span>
      ) : (
        <span className={styles.code} onClick={debounceFetchCode}>
          获取验证码
        </span>
      )}
    </div>
  )
  const step3 = (
    <div className={styles.stepsBox}>
      <div className={styles.stepTitle}>
        <span className="text-red mr-1">*</span>
        <span>登录邮箱</span>
        {formInfo.emailErr && <span className={styles.error}>请输入正确的邮箱</span>}
        {formInfo.codeErr && <span className={styles.error}>请输入正确的验证码</span>}
      </div>
      <div className={styles.emailBox}>
        <Input
          inputClass="input"
          defaultValue={formInfo.email}
          className={styles.emailInput}
          onChange={(e) => setFormInfo({ email: e.currentTarget.value })}
          placeholder="请输入邮箱"
        />
        <Input
          inputClass="input"
          defaultValue={formInfo.code}
          className={styles.codeInput}
          placeholder="验证码"
          onChange={(e) => setFormInfo({ code: e.currentTarget.value })}
          suffix={GetCodeDom}
        />
      </div>
      <div className={styles.stepTitle}>
        <span className="text-red mr-1">*</span>
        <span>密码</span>
        {formInfo.pwdErr && <span className={styles.error}>密码格式不符合要求，请重新输入</span>}
        {formInfo.repwdErr && <span className={styles.error}>两次密码不一致，请重新输入</span>}
      </div>
      <div className={styles.tips}>须是6-20个英文字母、数字，且以上两种必须都包含</div>
      <Input
        inputClass="input"
        id="pwd"
        defaultValue={formInfo.password}
        onChange={(e) => setFormInfo({ password: e.currentTarget.value })}
        placeholder="请输入密码"
        hasSuffix
      />
      <Input
        inputClass="input"
        id="pwdSecond"
        defaultValue={formInfo.repwd}
        className="mt-2"
        placeholder="请再次输入密码"
        onChange={(e) => setFormInfo({ repwd: e.currentTarget.value })}
        hasSuffix
      />
      <div className={styles.stepTitle}>
        <span className="text-red mr-1">*</span>
        <span>请至少填写一种联系方式</span>
        {formInfo.contractError && <span className={styles.error}>请至少输入一项联系方式</span>}
      </div>
      <Input
        inputClass="input"
        className="mb-2"
        defaultValue={formInfo.telegram}
        placeholder="Telegram:"
        onChange={(e) => setFormInfo({ telegram: e.currentTarget.value })}
      />
      <Input
        inputClass="input"
        className="mb-2"
        defaultValue={formInfo.whatsapp}
        placeholder="Whatsapp:"
        onChange={(e) => setFormInfo({ whatsapp: e.currentTarget.value })}
      />
      <Input
        inputClass="input"
        placeholder="微信:"
        defaultValue={formInfo.wechat}
        onChange={(e) => setFormInfo({ wechat: e.currentTarget.value })}
      />
    </div>
  )

  return (
    <div className={styles.enter}>
      <div className={styles.stepBox}>
        {[1, 2, 3].map((item, index) => {
          return (
            <Fragment key={item}>
              {!!index && <span className={styles.line}></span>}
              <div
                className={cm(styles.step, item === formInfo.step ? styles.stepActive : '')}
                onClick={() => setFormInfo({ step: item })}
              >
                <span className={styles.span}>{item}</span>
              </div>
            </Fragment>
          )
        })}
      </div>
      {formInfo.step === 1 && step1}
      {formInfo.step === 2 && step2}
      {formInfo.step === 3 && step3}
      <Button className={styles.submit} onClick={onSubmit}>
        {formInfo.step === 3 ? '提交' : '下一步'}
      </Button>
    </div>
  )
}

export default Index
